import paramiko
import time
from type import *
import pandas as pd
import redfish
import subprocess
import base64
import requests

def send_msg(ssh, command, end_flag):
    shell = ssh.invoke_shell()
    shell.settimeout(0)     # 设置非阻塞模式
    shell.send(command + "\n")  # 替换为你需要执行的命令
    # 初始化变量
    output = ""
    start_time = time.time()    # 记录命令发送时间
    
    # 循环接收输出，直到命令执行完成
    while True:
        if shell.recv_ready():  # 检查是否有输出可读
            output += shell.recv(1024).decode()     # 读取输出
            if end_flag in output:  
                break
        else:
            time.sleep(0.1) # 短暂等待，避免 CPU 过载
            
        if time.time() - start_time > 60:  # 如果超过60秒未收到结束标志，则认为命令执行失败
            return "", TIME_ERROR
        
    end_time = time.time() - start_time
    
    return output, end_time
    
    
def create_redfish_obj(ip_host, account, pwd):
    while True:
        try:
            client = redfish.redfish_client(base_url="https://" + ip_host + ":10443", username=account, password=pwd, default_prefix='/redfish/v1/')
            client.login(auth="session")
            return client
        except Exception as e:
            print(f"无法连接到 Redfish 服务: {e}")
            # return None
    
    
def send_redfish_Getmsg(redfish_obj, req):
    start_time = time.time()
    try:
        response = redfish_obj.get(req, None)    
    except redfish.exceptions.ServerError as e:
        print(f"发送redfish请求 服务器错误: {e}")
        response = e.response
    response_time = time.time() - start_time
    
    return response, response_time


def get_auth_header(username, password):
    encode_info = base64.b64encode('{}:{}'.format(
        username, password).encode('utf-8')).decode('utf-8')
    return {"Authorization": "Basic {}".format(encode_info)}


def do_get(ip, port, auth, uri):
    req_url = 'https://{}:{}{}'.format(ip, port, uri)
    start_time = time.time()
    try:
        rsp = requests.get(
            url=req_url, headers=get_auth_header(auth[0], auth[1]), auth=auth, verify=False, timeout=(2, 30))
        return rsp, time.time() - start_time
    except requests.exceptions.RequestException as e:
        print(e)
        return None, time.time() - start_time
    
    
def do_get_UI(ip, port, auth, uri, header):
    req_url = 'https://{}:{}{}'.format(ip, port, uri)
    start_time = time.time()
    try:
        rsp = requests.get(
            url=req_url, headers=header, auth=auth, verify=False, timeout=(2, 30))
        return rsp, time.time() - start_time
    except requests.exceptions.RequestException as e:
        print(e)
        return None, time.time() - start_time

def save_report(hostname, data, cpu_cores, memory_size):
    # 将数据转换为列表形式
    rows = []
    for command, response_time in data.items():
        rows.append({
            "访问ip": hostname,
            "cpu核心数": cpu_cores,
            "内存大小": memory_size,
            "命令": command,
            "响应时间": str(response_time)
        })
        
    # 将数据转换为DataFrame
    df = pd.DataFrame(rows)
    timestep = time.time()
    # 将 DataFrame 写入 Excel 文件
    output_file = "./result/output_{}.xlsx".format(timestep)
    df.to_excel(output_file, index=False, engine="openpyxl")



